﻿using LiveCharts.Wpf;
using LiveCharts;
using Parylene_CVD.Commands;
using Parylene_CVD.Model;
using Parylene_CVD.Service;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using DataProcesss.model;
using DataProcesss;
using System.Collections.ObjectModel;

using Parylene_CVD.DAL;
using Microsoft.Win32;
using System.Windows;

namespace Parylene_CVD.ViewModel
{
    public class DataCurveViewModel : ViewModelBase
    {
        public DataCurveViewModel(NavigationService DeviceMonitorViewNavigationService, NavigationService DataRecordViewNavigationService, NavigationService AlarmEventViewNavigationService, NavigationService HomeViewNavigationService) {
            MonitorCommand = new NavigateCommand(DeviceMonitorViewNavigationService);
            DataRecordCommand = new NavigateCommand(DataRecordViewNavigationService);
            AlarmEventCommand = new NavigateCommand(AlarmEventViewNavigationService);
            ExitCommand = new NavigateCommand(HomeViewNavigationService);
            OpenFileDialogCommand = new RelayCommand(OpenFileDialog);
            UpdateStartTimeCommand = new RelayCommand(UpdateStartTime);
            SelectAllCommand = new RelayCommand(SelectAll);
            DeselectAllCommand = new RelayCommand(DeselectAll);
            UpdateSelectedColumnsCommand = new RelayCommand(UpdateSelectedColumns);
            SelectedColumns = new ObservableCollection<CheckBoxData>();
            DeviceName = GlobalVariables.CurDeviceName;
            StartTime = DateTime.Now;
            EndTime = DateTime.Now;
            SetDefaultFolderPath();
            TitleSet();
            DataSource = new ObservableCollection<Data>();
            YAxisLabelFormatter = value => value.ToString("F2");  //设置纵坐标数据格式为保存小数点后两位
        }

        public Func<double, string> YAxisLabelFormatter { get; set; }
        public ICommand? MonitorCommand { get; }
        public ICommand? DataRecordCommand { get; }
        public ICommand? DataCurveCommand { get; }
        public ICommand? AlarmEventCommand { get; }
        public ICommand? ExitCommand { get; }
        //选择文件按钮命令
        public ICommand OpenFileDialogCommand { get; }
        //选中全选按钮执行命令
        public ICommand SelectAllCommand { get; }
        //取消选中全选按钮执行命令
        public ICommand DeselectAllCommand { get; }
        //选中或取消复选框执行命令
        public ICommand UpdateSelectedColumnsCommand { get; set; }
        //点击确认按钮执行命令
        public ICommand UpdateStartTimeCommand { get; private set; }
        //点击确认按钮执行方法，如果开始时间小于结束时间弹出提示框，否则根据时间段更新数据
        private void UpdateStartTime(object obj)
        {
            if (_startTime < _endTime)
            {
                GetData(_startTime, _endTime);
            }
            else
            {
                MessageBox.Show($"结束时间不能小于开始时间");
            }
        }
        //全选按下执行方法
        private void SelectAll(object obj)
        {
            foreach (var checkBoxData in Columns)
            {
                checkBoxData.IsChecked = true;
                UpdateSelectedColumns(checkBoxData);
            }
        }
        //取消全选执行方法
        private void DeselectAll(object obj)
        {
            foreach (var checkBoxData in Columns)
            {
                checkBoxData.IsChecked = false;
                UpdateSelectedColumns(checkBoxData);
            }
        }
        // 选择文件执行方法
        private void OpenFileDialog(object obj)
        {
            RealtimeData datasave = new RealtimeData();
            var openFileDialog = new OpenFileDialog
            {
                InitialDirectory = DefaultFolderPath, // 默认打开的文件夹路径
            };

            if (openFileDialog.ShowDialog() == true)
            {
                // 获取选择的文件路径
                FilePath = openFileDialog.FileName;
                // 获取文件名（不包括路径和扩展名）
                SelectedFileName = System.IO.Path.GetFileNameWithoutExtension(FilePath);
                
                DataSource = datasave.GetData(FilePath);
                if (DataSource.Count > 0)
                {
                    StartTime = DateTime.Parse(DataSource[0].Time);
                    EndTime = DateTime.Parse(DataSource[DataSource.Count - 1].Time);
                    GetData(StartTime, EndTime);
                }
               
            }
        }
        //选中或取消复选框执行方法
        private void UpdateSelectedColumns(object parameter)
        {
            CheckBoxData checkBoxData = parameter as CheckBoxData;
            if (checkBoxData != null)
            {
                var seriesToUpdate = SeriesCollection.FirstOrDefault(s => s.Title == checkBoxData.Content);
                if (seriesToUpdate != null)
                {
                    if (checkBoxData.IsChecked)
                    {
                        if (!SeriesCollection.Contains(seriesToUpdate))
                        {
                            SeriesCollection.Add(seriesToUpdate);
                        }
                        if (!SelectedColumns.Contains(checkBoxData))
                        {
                            SelectedColumns.Add(checkBoxData);
                        }
                    }
                    else
                    {
                        if (SeriesCollection.Contains(seriesToUpdate))
                        {
                            SeriesCollection.Remove(seriesToUpdate);
                        }
                        if (SelectedColumns.Contains(checkBoxData))
                        {
                            SelectedColumns.Remove(checkBoxData);
                        }
                    }
                }
                else if (checkBoxData.IsChecked)
                {
                    var seriesToAdd = new LineSeries
                    {
                        Title = checkBoxData.Content,
                        Values = new ChartValues<double>(_dataSource.Select(d => GetColumnValue(d, checkBoxData.Content))),
                    };
                    SeriesCollection.Add(seriesToAdd);
                    if (!SelectedColumns.Contains(checkBoxData))
                    {
                        SelectedColumns.Add(checkBoxData);
                    }
                }
            }
            GetData(_startTime, _endTime);
        }
        // 设备名
        private string? _deviceName;
        public string? DeviceName
        {
            get => _deviceName;
            set
            {
                _deviceName = value;
                OnPropertyChanged(nameof(DeviceName));
            }
        }
        //复选框所有项
        private List<CheckBoxData> _columns;
        public List<CheckBoxData> Columns
        {
            get { return _columns; }
            set
            {
                _columns = value;
                OnPropertyChanged("Columns");
            }
        }
        //复选框选中项
        private ObservableCollection<CheckBoxData> _selectedColumns;
        public ObservableCollection<CheckBoxData> SelectedColumns
        {
            get { return _selectedColumns; }
            set
            {
                _selectedColumns = value;
                OnPropertyChanged("SelectedColumns");
                GetData(_startTime, _endTime);
            }
        }
        //开始时间
        private DateTime _startTime;
        public DateTime StartTime
        {
            get { return _startTime; }
            set
            {
                _startTime = value;
                OnPropertyChanged("StartTime");
            }
        }
        //结束时间
        private DateTime _endTime;
        public DateTime EndTime
        {
            get { return _endTime; }
            set
            {
                _endTime = value;
                OnPropertyChanged("EndTime");
            }
        }
        //根据开始结束时间在文件中获取的数据
        private ObservableCollection<Data> _dataSource;
        public ObservableCollection<Data> DataSource
        {
            get { return _dataSource; }
            set
            {
                _dataSource = value;
                OnPropertyChanged("DataSource");
            }
        }
        //文件完整路径
        public string _FilePath;
        public string FilePath
        {
            get { return _FilePath; }
            set { _FilePath = value; OnPropertyChanged(nameof(FilePath)); }
        }
        //文件名
        private string _selectedFileName;
        public string SelectedFileName
        {
            get => _selectedFileName;
            set
            {
                _selectedFileName = value;
                OnPropertyChanged(nameof(SelectedFileName));
            }
        }

        // 默认文件夹路径--->通常为数据库中存储路径拼接当前设备名
        public string DefaultFolderPath { get; set; }
        public void SetDefaultFolderPath()
        {
            ParameterDAL parameterDAL = new ParameterDAL();
            string BasePath =  parameterDAL.GetParameter("ParameterName = '数据保存目录'", "")[0].ParameterValue;
            DefaultFolderPath = System.IO.Path.Combine(BasePath, DeviceName);
        }

        public SeriesCollection SeriesCollection { get; set; }
        public string[] Labels { get; set; }
        //根据开始和结束时间获取复选框选中的数据显示在曲线图中
        public void GetData(DateTime startTime, DateTime endTime)
        {
            RealtimeData datasave = new RealtimeData();
            // 将开始时间和结束时间转换为字符串
            string startTimeStr = startTime.ToString("yyyy-MM-dd HH:mm:ss");
            string endTimeStr = endTime.ToString("yyyy-MM-dd HH:mm:ss");
            // 创建 SeriesCollection：绑定到图像显示的数据
            SeriesCollection = new SeriesCollection();
            // 使用开始时间和结束时间来选择数据
            if (FilePath != null)
            {
                
                _dataSource = datasave.GetData(FilePath);
                _dataSource = datasave.DataSelect(_dataSource, startTimeStr, endTimeStr);
                // 数据减采样
                List<Data> dataSourceList = _dataSource.ToList();
                int n = dataSourceList.Count > 100 ? (int)Math.Ceiling(dataSourceList.Count / 100.0) : 1;
                _dataSource = new ObservableCollection<Data>(dataSourceList.Where((x, i) => i % n == 0));

                if (_dataSource != null)
                {
                    //获取横轴信息
                    Labels = _dataSource.Select(d => d.Time.Substring(5)).ToArray();
                    OnPropertyChanged("Labels");

                    Dictionary<string, ChartValues<double>> precomputedValues = new Dictionary<string, ChartValues<double>>();
                    foreach (CheckBoxData checkBoxData in Columns)
                    {
                        precomputedValues[checkBoxData.Content] = new ChartValues<double>(_dataSource.Select(d => GetColumnValue(d, checkBoxData.Content)));
                    }

                    // 为每一列数据创建一个 LineSeries
                    foreach (CheckBoxData checkBoxData in Columns)
                    {
                        LineSeries series = new LineSeries
                        {
                            Title = checkBoxData.Content,
                            Values = precomputedValues[checkBoxData.Content],
                            // 如果Title以"温度"结尾，使用第一个Y轴（索引为0）
                            // 如果Title以"压力"结尾，使用第二个Y轴（索引为1）
                            ScalesYAt = checkBoxData.Content.EndsWith("压力") || checkBoxData.Content.EndsWith("sure") || checkBoxData.Content.EndsWith("Pump") ? 1 : 0,

                        };
                        if (checkBoxData.IsChecked)
                        {
                            SeriesCollection.Add(series);
                        }
                        else
                        {
                            SeriesCollection.Remove(series);
                        }
                    }
                    OnPropertyChanged("SeriesCollection");
                }
            }
            else // 当 FilePath 为空时，清空 SeriesCollection 和 Labels
            {
                SeriesCollection.Clear();
                Labels = new string[0];
                OnPropertyChanged("SeriesCollection");
                OnPropertyChanged("Labels");
            }
        }



        //根据列名选择对应的数据
        private double GetColumnValue(Data data, string column)
        {
            double value;
            switch (column)
            {
                case "炉盖温度":
                case "Lid":
                    value = data.FurnaceCoverTemperature;
                    break;
                case "炉管温度1":
                case "Tube1":
                    value = data.FurnaceTubeTemperature1;
                    break;
                case "炉管温度2":
                case "Tube2":
                    value = data.FurnaceTubeTemperature2;
                    break;
                case "蒸发温度1":
                case "Evaporation1":
                    value = data.EvaporationTemperature1;
                    break;
                case "蒸发温度2":
                case "Evaporation2":
                    value = data.EvaporationTemperature2;
                    break;
                case "蒸发温度3":
                case "Evaporation3":
                    value = data.EvaporationTemperature3;
                    break;
                case "裂解温度1":
                case "Pyrolysis1":
                    value = data.CrackingTemperature1;
                    break;
                case "裂解温度2":
                case "Pyrolysis2":
                    value = data.CrackingTemperature2;
                    break;
                case "裂解温度3":
                case "Pyrolysis3":
                    value = data.CrackingTemperature3;
                    break;
                case "辅热温度":
                case "Auxiliary":
                    value = data.AuxiliaryHeatingTemperature;
                    break;
                case "冷冻温度":
                case "Freezing":
                    value = data.FreezingTemperature;
                    break;
                case "沉积室压力":
                case "DepPressure":
                    value = data.BinPressure;
                    break;
                case "真空泵压力":
                case "VacuumPump":
                    value = data.PumpPressure;
                    break;
                case "舱壁温度":
                case "Bin":
                    value = data.SilowallTemperature;
                    break;
                case "偶联温度":
                case "Coupling":
                    value = data.CouplingTemperature;
                    break;
                default:
                    value = 0;
                    break;
            }
            return value;
        }



        public string Start_Title { get; set; }
        public string End_Title { get; set; }
        public string SelectAll_Title { get; set; }
        public string Confirm_Title { get; set; }
        public string SelectFile_Title { get; set; }
        public string Time_Title { get; set; }
        public string Temperature_Title { get; set; }
        public string Pressure_Title { get; set; }
        public string Exit_Title { get; set; }
        private void TitleSet()
        {
            _columns = new List<CheckBoxData>{
                            new CheckBoxData { Content = "炉盖温度", IsChecked = true },
                            new CheckBoxData { Content = "炉管温度1", IsChecked = false },
                            new CheckBoxData { Content = "炉管温度2", IsChecked = false },
                            new CheckBoxData { Content = "蒸发温度1", IsChecked = true },
                            new CheckBoxData { Content = "蒸发温度2", IsChecked = false },
                            new CheckBoxData { Content = "蒸发温度3", IsChecked = false },
                            new CheckBoxData { Content = "裂解温度1", IsChecked = false },
                            new CheckBoxData { Content = "裂解温度2", IsChecked = false },
                            new CheckBoxData { Content = "裂解温度3", IsChecked = false },
                            new CheckBoxData { Content = "辅热温度", IsChecked = false },
                            new CheckBoxData { Content = "冷冻温度", IsChecked = false },
                            new CheckBoxData { Content = "舱壁温度", IsChecked = false },
                            new CheckBoxData { Content = "偶联温度", IsChecked = false },
                            new CheckBoxData { Content = "沉积室压力", IsChecked = false },
                            new CheckBoxData { Content = "真空泵压力", IsChecked = false }
            };
            Start_Title = "开始:";
            End_Title = "结束:";
            SelectAll_Title = "全选";
            Confirm_Title = "确认";
            SelectFile_Title = "选择文件:";
            Time_Title = "时间";
            Temperature_Title = "温度/℃";
            Pressure_Title = "压力/Pa";
            Exit_Title = "退出";
            
        }
    }
}
